<template>
  <div class="patient-profile-container">
    <el-card class="profile-card animated-fade-in">
      <template #header>
        <div class="card-header">
          <span class="card-title">我的个人信息</span>
          <div class="actions">
            <el-button v-if="!isEditing" type="primary" :icon="Edit" @click="toggleEdit">编辑资料</el-button>
            <div v-else>
              <el-button type="success" :icon="Check" @click="savePatientInfo">保存修改</el-button>
              <el-button :icon="Close" @click="toggleEdit">取消</el-button>
            </div>
          </div>
        </div>
      </template>
      <el-form :model="patientInfo" ref="patientFormRef" :rules="formRules" label-width="120px" :disabled="!isEditing" class="profile-form">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="patientInfo.name" placeholder="请输入姓名" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="patientInfo.phone" placeholder="请输入手机号" clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="修改密码">
              <el-input type="password" v-model="patientInfo.password" placeholder="留空则不修改密码" show-password clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="年龄" prop="age">
              <el-input-number v-model="patientInfo.age" :min="0" :max="150" controls-position="right" style="width: 100%;"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-radio-group v-model="patientInfo.gender">
                <el-radio label="男" border>男</el-radio>
                <el-radio label="女" border>女</el-radio>
                <el-radio label="其他" border>其他</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出生日期" prop="birthDate">
              <el-date-picker
                  v-model="patientInfo.birthDate"
                  type="date"
                  placeholder="选择出生日期"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  style="width: 100%;"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="诊断年龄" prop="diagnoseAge">
              <el-input-number v-model="patientInfo.diagnoseAge" :min="0" :max="patientInfo.age || 150" controls-position="right" style="width: 100%;"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="省份" prop="province">
              <el-input v-model="patientInfo.province" placeholder="请输入省份" clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="城市" prop="city">
              <el-input v-model="patientInfo.city" placeholder="请输入城市" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-f :span="12">
            <el-form-item label="区/县" prop="district">
              <el-input v-model="patientInfo.district" placeholder="请输入区/县" clearable></el-input>
            </el-form-item>
          </el-f>
        </el-row>

        <el-form-item label="详细地址" prop="detailedAddress">
          <el-input type="textarea" v-model="patientInfo.detailedAddress" :rows="3" placeholder="请输入详细地址" clearable></el-input>
        </el-form-item>

        <el-divider content-position="left">系统信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="创建时间">
              <el-tag type="info">{{ formatDateTime(patientInfo.created) }}</el-tag>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="更新时间">
              <el-tag type="info">{{ formatDateTime(patientInfo.updated) }}</el-tag>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, watch } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import { Edit, Check, Close } from '@element-plus/icons-vue' // Import icons

// --- Data Definitions ---
const patientInfo = ref({
  id: null,
  name: '',
  phone: '',
  password: '', // For password modification
  age: null,
  gender: '',
  birthDate: '',
  diagnoseAge: null,
  province: '',
  city: '',
  district: '',
  detailedAddress: '',
  created: '',
  updated: '',
  deleted: false,
})

const originalPatientInfo = ref(null) // Stores original data for cancellation

const isEditing = ref(false)

const userId = ref(localStorage.getItem('userId')) // Ensure fetching from localStorage

// Form Validation Rules
const formRules = reactive({
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号', trigger: 'blur' }
  ],
  gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
  birthDate: [{ required: true, message: '请选择出生日期', trigger: 'change' }],
  province: [{ required: true, message: '请输入省份', trigger: 'blur' }],
  city: [{ required: true, message: '请输入城市', trigger: 'blur' }],
  district: [{ required: true, message: '请输入区/县', trigger: 'blur' }],
  detailedAddress: [{ required: true, message: '请输入详细地址', trigger: 'blur' }],
})

const patientFormRef = ref(null) // Reference to the form

// --- Method Definitions ---

// Fetch Patient Details
const fetchPatientInfo = async () => {
  if (!userId.value) {
    ElMessage.error('无法获取患者ID，请尝试重新登录或联系管理员。')
    return
  }
  try {
    // 1. Fetch Basic Info
    const basicInfoResponse = await axios.get(`http://localhost:8080/user/${userId.value}`)
    if (basicInfoResponse.data.code !== 200) {
      ElMessage.error(`获取基本信息失败: ${basicInfoResponse.data.msg || '未知错误'}`)
      return;
    }
    const basicData = basicInfoResponse.data.data;

    // 2. Fetch Detailed Info
    const detailInfoResponse = await axios.get(`http://localhost:8080/userdetail/${userId.value}`)
    if (detailInfoResponse.data.code !== 200) {
      // It's possible user_detail doesn't exist yet for a new user,
      // so we might treat 404 differently if we want to allow creating it.
      // For now, treat it as an error.
      ElMessage.error(`获取详细信息失败: ${detailInfoResponse.data.msg || '未知错误'}`)
      // If no detail is found, initialize with empty values for detail-specific fields
      // This prevents errors if detailData is null
      Object.assign(patientInfo.value, basicData, {
        age: null, gender: '', birthDate: '', diagnoseAge: null,
        province: '', city: '', district: '', detailedAddress: ''
      });
      patientInfo.value.password = ''; // Clear password field for security
      originalPatientInfo.value = structuredClone(patientInfo.value);
      return; // Stop here if detail info failed
    }
    const detailData = detailInfoResponse.data.data;

    // 3. Merge Data
    const mergedData = {
      ...basicData,
      ...detailData, // Detail data fields will overwrite basic data fields if names are the same
    };

    patientInfo.value = structuredClone(mergedData);
    patientInfo.value.password = ''; // Clear password field for security

    // Save a copy of the original data
    originalPatientInfo.value = structuredClone(patientInfo.value);

    ElMessage.success('患者信息获取成功！');

  } catch (error) {
    console.error('获取患者信息时发生错误:', error);
    ElMessage.error('获取患者信息失败，请检查网络或服务器。');
  }
}

// Toggle Edit Mode
const toggleEdit = () => {
  isEditing.value = !isEditing.value
  if (!isEditing.value) {
    // If exiting edit mode (clicking cancel), restore original data
    if (originalPatientInfo.value) {
      patientInfo.value = structuredClone(originalPatientInfo.value);
    }
    patientFormRef.value?.resetFields(); // Reset form validation state
  }
}

// Save Modifications
const savePatientInfo = async () => {
  try {
    await patientFormRef.value.validate(); // Trigger form validation

    // Build payload for basic info update
    const basicUpdatePayload = {
      id: patientInfo.value.id,
      name: patientInfo.value.name,
      phone: patientInfo.value.phone,
    };
    // Only include password if it's not empty
    if (patientInfo.value.password) {
      basicUpdatePayload.password = patientInfo.value.password;
    }

    // Build payload for detailed info update
    const detailUpdatePayload = {
      id: patientInfo.value.id,
      age: patientInfo.value.age,
      gender: patientInfo.value.gender,
      birthDate: patientInfo.value.birthDate,
      diagnoseAge: patientInfo.value.diagnoseAge,
      province: patientInfo.value.province,
      city: patientInfo.value.city,
      district: patientInfo.value.district,
      detailedAddress: patientInfo.value.detailedAddress,
    };

    // 1. Call basic info update API
    const basicUpdateResponse = await axios.post('http://localhost:8080/user/modify', basicUpdatePayload);

    if (basicUpdateResponse.data.code !== 200) {
      ElMessage.error(`更新基本信息失败: ${basicUpdateResponse.data.msg}`);
      return; // If basic info update fails, stop
    }

    // 2. Call detailed info update API
    // The userdetail API might need to handle both creation (if not exists) and update
    // For now, assuming 'update' also covers creation if the ID is provided and not found.
    const detailUpdateResponse = await axios.post('http://localhost:8080/userdetail/update', detailUpdatePayload);

    if (detailUpdateResponse.data.code !== 200) {
      ElMessage.error(`更新详细信息失败: ${detailUpdateResponse.data.msg}`);
      return; // If detailed info update fails, stop
    }

    ElMessage.success('患者信息更新成功！'); // Only succeed if both APIs are successful
    isEditing.value = false; // Exit edit mode
    await fetchPatientInfo(); // Re-fetch the latest data

  } catch (error) {
    console.error('更新患者信息时发生错误:', error);
    if (error.isAxiosError) {
      ElMessage.error('提交失败，请检查网络或服务器。');
    } else {
      ElMessage.error('表单校验失败，请检查输入项。');
    }
  }
}

// Format Date and Time
const formatDateTime = (dateTimeString) => {
  if (!dateTimeString) return ''
  const date = new Date(dateTimeString);
  if (isNaN(date.getTime())) return dateTimeString;

  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

onMounted(() => {
  fetchPatientInfo()
})

watch(userId, (newVal, oldVal) => {
  if (newVal && newVal !== oldVal) {
    fetchPatientInfo();
  }
});
</script>

<style scoped>
.patient-profile-container {
  padding: 30px; /* Increased padding */
  background-color: #f8fbfd; /* Light background */
  min-height: calc(100vh - 60px); /* Adjust height for main layout */
  display: flex;
  justify-content: center; /* Center the card */
  align-items: flex-start; /* Align card to top */
}

.profile-card {
  width: 100%;
  max-width: 900px; /* Max width for readability */
  border-radius: 12px; /* Rounded corners */
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1); /* Deeper shadow */
  background-color: #ffffff; /* White background for card */
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5; /* Separator */
  margin-bottom: 20px;
}

.card-title {
  font-size: 26px; /* Larger title */
  font-weight: bold;
  color: #333;
}

.actions .el-button {
  border-radius: 8px; /* Rounded buttons */
  padding: 10px 20px; /* Button padding */
  font-size: 15px;
}

.profile-form {
  padding: 0 10px; /* Slight horizontal padding for form content */
}

.el-form-item {
  margin-bottom: 22px; /* Consistent spacing */
}

.el-input,
.el-date-picker,
.el-input-number {
  width: 100%; /* Full width for inputs */
}

/* Style for radio group options */
.el-radio-group {
  display: flex; /* Makes radios display in a row */
  gap: 10px; /* Space between radio buttons */
}

.el-radio.is-bordered {
  border-radius: 6px;
  padding: 8px 15px;
}

.el-divider {
  margin: 30px 0; /* Spacing for dividers */
  font-size: 16px;
  color: #606266;
  font-weight: 500;
}

.el-tag {
  font-size: 14px;
  padding: 8px 12px;
  height: auto; /* Allow tag height to adjust */
}

/* Animation for card entry */
.animated-fade-in {
  opacity: 0;
  transform: translateY(20px);
  animation: fadeInMoveUp 0.6s ease-out forwards;
}

@keyframes fadeInMoveUp {
  from { opacity: 0; transform: translateY(20px); }
  to { opacity: 1; transform: translateY(0); }
}
</style>